package com.jason.quectel;

/**
 * @author：Jason
 * @date：2022/3/8 13:16
 * @email：1129847330@qq.com
 * @description:
 */
public class SynchronizedDemo {
    private int amount;

    public int getAmount() {
        return amount;
    }

    public void add(int num) {
        synchronized (this) {
            amount += num;
            System.out.println("存入成功，余额：" + amount);
        }
    }

    public synchronized void sub(int num) {
        synchronized (this) {
            if (amount >= num) {
                amount -= num;
                System.out.println("取出成功,当前余额：" + amount);
            } else {
                System.out.println("余额不足,当前余额：" + amount);
            }
        }
    }

    public static void main(String[] args) {
        SynchronizedDemo synchronizedDemo = new SynchronizedDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        synchronizedDemo.add(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                        synchronizedDemo.sub(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}